self.importScripts(
    './spark-md5.js'
);

self.onmessage = e => {
    const { chunks } = e.data;
    const spark = new self.SparkMD5.ArrayBuffer();
    let percentage = 0;
    let count = 0;
    const reader = new FileReader();

    const loadNext = index => {
        reader.readAsArrayBuffer(chunks[index].file);
        reader.onload = e => {
            count++;
            spark.append(e.target.result);
            const chunkHash = self.SparkMD5.ArrayBuffer.hash(e.target.result);
            if (count === chunks.length) {
                self.postMessage({
                    percentage: 100,
                    hash: spark.end(),
                    index,
                    chunkHash
                });
                self.close();
            } else {
                percentage = count / chunks.length * 100;
                console.log(percentage);
                self.postMessage({
                    percentage,
                    index,
                    chunkHash
                });
                loadNext(count);
            }
        };
    };
    loadNext(0);
};
